<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Http\Resources\CommentModelResource;
use App\Models\CommentModel;
use App\Models\DocumentModel;
use App\Models\UserModel;
use App\Utils\ControllerModelTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CommentController extends ApiController
{
    use ControllerModelTrait;

    /**
     * 获取评论列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getList(Request $request): JsonResponse
    {
        $Model = CommentModel::getModel($request);
        $paginate = $Model->orderByDesc('id')->paginate(20);
        return $this->success($this->getPaginate($paginate, CommentModelResource::collection($paginate->items())));
    }

    /**
     * 发布评论
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doSave(Request $request): JsonResponse
    {
        $uid = $this->verifyInteger('uid');
        $did = $this->verifyInteger('did');
        $data = $request->only(['uid', 'did', 'pid', 'comment']);
        $user = UserModel::where('id', $uid)->select(['username', 'nickname'])->first();
        if ($user)
            $data = array_merge($data, $user->toArray());
        CommentModel::create($data);
        DocumentModel::where('id', $did)->increment('comment_count');
        return $this->success();
    }

    /**
     * 删除评论
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doDelete(): JsonResponse
    {
        $did = $this->verifyInteger('did');
        CommentModel::where('id', $did)->delete();
        DocumentModel::where('id', $did)->decrement('comment_count');
        return $this->success();
    }
}
